package com.qk.management.service.decorator;

import com.qk.common.constants.AvatarMessageConstants;
import com.qk.common.storage.FileStorageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
public class LoggingFileStorageDecorator implements FileStorageStrategy {
    private final FileStorageStrategy delegate;
    
    public LoggingFileStorageDecorator(FileStorageStrategy delegate) {
        this.delegate = delegate;
    }
    
    @Override
    public String storeFile(MultipartFile file) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("{}: {}", AvatarMessageConstants.FILE_STORAGE_START, file.getOriginalFilename());
        
        try {
            String result = delegate.storeFile(file);
            long endTime = System.currentTimeMillis();
            log.info("{}: {}, {}: {}ms", AvatarMessageConstants.FILE_STORAGE_SUCCESS, file.getOriginalFilename(), AvatarMessageConstants.FILE_STORAGE_DURATION, (endTime - startTime));
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.error("{}: {}, {}: {}ms, {}: {}", AvatarMessageConstants.FILE_STORAGE_FAILURE, file.getOriginalFilename(), AvatarMessageConstants.FILE_STORAGE_DURATION, (endTime - startTime), AvatarMessageConstants.FILE_STORAGE_ERROR, e.getMessage());
            throw e;
        }
    }
    
    @Override
    public void deleteFile(String fileUrl) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("{}: {}", AvatarMessageConstants.FILE_DELETION_START, fileUrl);
        
        try {
            delegate.deleteFile(fileUrl);
            long endTime = System.currentTimeMillis();
            log.info("{}: {}, {}: {}ms", AvatarMessageConstants.FILE_DELETION_SUCCESS, fileUrl, AvatarMessageConstants.FILE_STORAGE_DURATION, (endTime - startTime));
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.error("{}: {}, {}: {}ms, {}: {}", AvatarMessageConstants.FILE_DELETION_FAILURE, fileUrl, AvatarMessageConstants.FILE_STORAGE_DURATION, (endTime - startTime), AvatarMessageConstants.FILE_STORAGE_ERROR, e.getMessage());
            throw e;
        }
    }
    
    @Override
    public boolean doesFileExist(String fileUrl) {
        log.info("{}: {}", AvatarMessageConstants.FILE_EXISTENCE_CHECK, fileUrl);
        return delegate.doesFileExist(fileUrl);
    }
}